/* eslint-disable @typescript-eslint/no-unused-vars */
import {
  List,
  Modal,
  Radio,
  Checkbox,
  Icon,
  InputItem,
  Button
} from 'antd-mobile-v2';
import * as React from 'react';
import { Props, State } from '../type';
import {
  GetDataByExternalUrl,
  GetDataByExternalUrlR
} from '../../../../common/services';
import './index.less';
import noDataImg from '@/assets/images/no-data.png';
import { List as VList, ListRowProps } from 'react-virtualized';
import AutoSizer from 'react-virtualized/dist/commonjs/AutoSizer';
import AntdRefreshList from '@/components/antd-refresh-list';
import {
  getRelateProjectList,
  getProjectFeeRel,
  getAllowRucMatterList,
  GetProvideList,
  CostTypeInterface,
  getPaymentMethod
} from '@/services/laber-declare';

let debounceTimer = null;

class AddMatterModal extends React.Component<Props, State> {
  public static defaultProps = new Props();
  public state = new State();
  prevData: string;
  autoFocusInst: React.RefObject<HTMLInputElement>;
  constructor(props: Props) {
    super(props);
    this.state = {
      checkedList: [],
      matterIdList: [],
      isModal: false,
      options: [],
      sourceOptions: [], // 接口返回的未经处理的源数据
      checkedLabel: '',
      searchValue: '',
      loading: false,
      noData: false,
      otherParams: {} // 接口请求需要的其他参数（包括加载更多的参数）
    };
    this.prevData = '';
    this.autoFocusInst = React.createRef();
  }

  public componentDidUpdate(_prevProps, prevState) {
    if (this.props.externalOption?.searchWithoutData === false) {
      // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
      // @ts-ignore
      this.autoFocusInst.focus();
    }
  }

  public componentDidMount() {
    this.setDefaultData();
    // this.getMatterIdList();

    this.getExternalData();
  }

  getMatterIdList = async () => {
    const payload = {
      keyWord: '', // 搜索关键字
      lastId: '', // 最后一条数据主键
      pageNum: 1,
      pageSize: 200,
      triScope: this.props.triScope
    };
    const res = await getAllowRucMatterList(payload);
    const matterIdList = res.data.rows.map((item: any) => {
      // item.matterTotalUseAble = -0.11  // test
      let matterTotalUseAble = item.matterTotalUseAble;
      item.matterTotalUseAble =
        matterTotalUseAble < 0 ? -1 : matterTotalUseAble;

      return {
        text: item.matterName,
        value: item.id,
        descTitle: '事项余额：',
        descValue: item.matterTotalUseAble,
        disabled:
          (!item.matterTotalUseAble || item.matterTotalUseAble === 0) &&
          item.matterTotalUseAble !== -1,
        ...item
      };
    });

    this.setState({
      matterIdList
    });
  };

  setDefaultData = () => {
    const value = this.props.form?.getFieldValue(this.props.code);
    if (value) {
      this.setState({
        checkedList: value
      });
    }
  };

  private async getExternalData(val?: string) {
    // 是否有设置外部url
    if (
      this.props.useExternal &&
      this.props.externalOption &&
      this.props.externalOption.url
    ) {
      if (this.props.isDeclare) {
        if (
          this.props.externalOption?.searchWithoutData === false &&
          (val === undefined || val === '')
        ) {
          // 不允许不带参数请求接口
          this.setState({
            options: [],
            sourceOptions: []
          });
          return;
        }
        const { otherParams } = this.state;
        const params = {
          ...this.props.externalOption?.searchData,
          keyWord: val,
          ...otherParams,
          triScope: this.props.triScope
        };
        this.setState({ loading: true });
        const data = await GetDataByExternalUrlR(
          this.props.externalOption.url,
          params
        );

        let sourceList;
        let rows = data.rows || [];

        let list = rows.map((item: any) => {
          // item.matterTotalUseAble = -0.11  // test
          let matterTotalUseAble = item.matterTotalUseAble;
          item.matterTotalUseAble =
            matterTotalUseAble < 0 ? -1 : matterTotalUseAble;

          return {
            text: item.matterName,
            value: item.id,
            descTitle: '事项余额：',
            descValue: item.matterTotalUseAble,
            descTitle1: '关联公文：',
            descValue1: `[${item.orgName}][${item.documentCode}]`,
            disabled:
              (!item.matterTotalUseAble || item.matterTotalUseAble === 0) &&
              item.matterTotalUseAble !== -1,
            ...item
          };
        });

        if (list) {
          if (this.props.externalOption.enableLoadMore) {
            // 分页加载的情况
            const { options, sourceOptions } = this.state;
            this.setState({
              options: options.concat(list),
              sourceOptions: sourceOptions.concat(sourceList)
            });
          } else {
            this.setState({
              options: list,
              sourceOptions: sourceList
            });
          }
          if (list.length === 0) {
            this.setState({
              noData: true
            });
          }
        }

        this.setState({ loading: false, matterIdList: list });
      } else {
        this.setState({ loading: true });
        const data = await GetDataByExternalUrl(this.props.externalOption, {});
        if (data) {
          this.setState({
            options: data,
            sourceOptions: data,
            loading: false
          });
          if (data.length === 0) {
            this.setState({
              noData: true
            });
          }
        }
      }
    }
  }

  onClose = () => {
    this.setState({
      noData: false
    });
    this.props.hideAddModal();
    this.searchChange('');
  };

  handleSelectOk = () => {
    let { checkedList } = this.state;
    this.props.getMattersListFromModal(checkedList);

    this.onClose();
  };

  public closest(el: any, selector: any) {
    const matchesSelector =
      el.matches ||
      el.webkitMatchesSelector ||
      el.mozMatchesSelector ||
      el.msMatchesSelector;
    while (el) {
      if (matchesSelector.call(el, selector)) {
        return el;
      }
      el = el.parentElement;
    }
    return null;
  }

  onWrapTouchStart = (e: any) => {
    // fix touch to scroll background page on iOS
    if (!/iPhone|iPod|iPad/i.test(navigator.userAgent)) {
      return;
    }
    const pNode = this.closest(e.target, '.am-modal-content');
    if (!pNode) {
      e.preventDefault();
    }
  };

  searchChange = (val: any) => {
    this.setState({
      searchValue: val,
      otherParams: {
        lastId: ''
      },
      options: [],
      sourceOptions: []
    });
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(() => {
      this.getExternalData(val);
    }, 800);
  };

  handleRefresh = () => {
    console.log('handleRefresh');
  };

  handleLoadMore = () => {
    if (this.props.externalOption?.enableLoadMore) {
      const { sourceOptions } = this.state;
      this.setState(
        {
          otherParams: {
            lastId: sourceOptions[sourceOptions.length - 1]?.id || ''
          }
        },
        () => {
          this.getExternalData(this.state.searchValue);
        }
      );
    }
  };

  handleChecked = (e: any, item: any) => {
    const checked = e.target.checked;
    const checkedList = this.state.checkedList
      ? [...this.state.checkedList]
      : [];
    if (checked) {
      checkedList.push(item);
    } else {
      const i = checkedList.findIndex((ik: any) => ik.id === item.id);
      checkedList.splice(i, 1);
    }

    this.setState(
      {
        checkedList
      },
      () => {
        this.setState({
          matterIdList: [...this.state.matterIdList]
        });
      }
    );
  };

  setCheckedList = (checkedList: []) => {
    this.setState({
      checkedList
    });
  };
  public render() {
    const { getFieldProps } = this.props.form || {};
    let {
      error,
      form,
      name,
      code,
      required,
      placeholder,
      options,
      ...otherProps
    } = this.props || {};

    const { enableSearch } = this.props;
    const { searchValue } = this.state;
    const enableStyle = {
      color: '#222222'
    };
    const disabledStyle = {
      color: '#999999'
    };
    let { matterIdList, checkedList } = this.state;

    return (
      <Modal
        className='radioModal'
        visible={this.props.showAddModal}
        popup
        onClose={this.onClose}
        animationType='slide-up'
        wrapProps={{ onTouchStart: this.onWrapTouchStart }}
      >
        <List
          renderHeader={() => (
            <div className='modalTitle'>
              {'关联事项'}
              <Icon type='cross' className='closeIcon' onClick={this.onClose} />
            </div>
          )}
        >
          <List.Item>
            {this.props.externalOption?.url ? (
              <div className='radioSubTitle'>
                <InputItem
                  // {...this.props.form?.getFieldProps('keyword')}
                  value={this.state.searchValue}
                  clear
                  placeholder={this.props.externalOption?.placeholder}
                  maxLength={30}
                  onChange={this.searchChange}
                  ref={el => (this.autoFocusInst = el)}
                  onBlur={() => {
                    this.setState({
                      noData: false
                    });
                  }}
                ></InputItem>
              </div>
            ) : null}
            {matterIdList && matterIdList.length > 0 ? (
              <>
                <AntdRefreshList
                  height={window.screen.height - 192}
                  initialListSize={30}
                  dataSource={matterIdList}
                  refreshing={false}
                  loadingMore={false}
                  showFooterText={false}
                  enableRefresh={false}
                  paddingBottomstyle
                  noMargin
                  renderRow={(item, _sectionID, index) => {
                    item.label = item.text;
                    return (
                      <Checkbox.CheckboxItem
                        className={
                          item?.descTitle ? 'checkbox-input-list-descript' : ''
                        }
                        key={item.id}
                        checked={
                          this.state.checkedList.findIndex((val: any) => {
                            return val.id === item.id;
                          }) >= 0
                        }
                        onChange={(e: any) => {
                          // 先触发一次getFieldProps的onChange方法，标记当前表单已经被手动操作过，用于识别表单编辑后路由离开拦截
                          // if (fieldProps?.onChange) fieldProps?.onChange(e);
                          this.handleChecked(e, item);
                        }}
                        disabled={this.props.disabled || item?.disabled}
                      >
                        {!item?.descTitle ? (
                          item?.label
                        ) : (
                          <div
                            style={
                              this.props.disabled || item?.disabled
                                ? disabledStyle
                                : enableStyle
                            }
                          >
                            {item?.descValue !== -1 && (
                              <>
                                <div>
                                  <span
                                    className='title-text'
                                    style={{ maxWidth: '90%' }}
                                  >
                                    {item?.label}
                                  </span>
                                  {item?.descValue === 0 ? (
                                    <span className='tag-style'>余额不足</span>
                                  ) : null}
                                </div>
                                <div
                                  style={{ color: '#999', fontSize: '12px' }}
                                >
                                  {item?.descTitle +
                                    '' +
                                    (item?.descValue != undefined
                                      ? item?.descValue
                                      : '--')}
                                </div>
                                <div
                                  className='white-space'
                                  style={{ color: '#999', fontSize: '12px' }}
                                >
                                  <div>{item?.descTitle1}</div>
                                  <div className='flex-1'>
                                    {item?.descValue1}
                                  </div>
                                </div>
                              </>
                            )}
                            {item?.descValue === -1 && (
                              <>
                                <div>
                                  <span
                                    className='title-text'
                                    style={{ maxWidth: '90%' }}
                                  >
                                    {item?.label}
                                  </span>
                                </div>
                                <div style={{ fontSize: '12px' }}>
                                  {item?.descTitle + '不限额'}
                                </div>
                                <div
                                  className='white-space'
                                  style={{ fontSize: '12px' }}
                                >
                                  <div>{item?.descTitle1}</div>
                                  <div className='flex-1'>
                                    {item?.descValue1}
                                  </div>
                                </div>
                              </>
                            )}
                          </div>
                        )}
                      </Checkbox.CheckboxItem>
                    );
                  }}
                  onRefresh={this.handleRefresh}
                  onEndReached={this.handleLoadMore}
                />
                <div className={'ensureButtonWrap'}>
                  <span
                    key='ensure'
                    className={'ensureButton'}
                    onClick={this.handleSelectOk}
                  >
                    确定({checkedList.length})
                  </span>
                </div>
              </>
            ) : this.state.loading ? (
              <div className='loadingIconWrap'>
                <i className='iconfont iconjiazai' />
              </div>
            ) : enableSearch && !searchValue ? null : (
              <div style={{ textAlign: 'center' }}>
                <img
                  src={noDataImg}
                  alt=''
                  style={{ width: '120px', height: '120px' }}
                />
                <span style={{ display: 'block', color: '#B8B8B8' }}>
                  {this.props.notFoundContent || '暂无数据'}
                </span>
              </div>
            )}
          </List.Item>
        </List>
      </Modal>
    );
  }
}

export default AddMatterModal;
